#!/bin/bash
# /opt/amisnaps/fssnap.sh 7 vol-35da9515 10 x novalid
# this file generates the commands needed to run the fssnap.sh backup script. It dynamically gathers all
# the instances and builds the command strings. Many of the paramters are not used because the Amisnap
# script was never finished and validation doesn't work. Validation doesn't function which means a lot
# of the CLI paramters are unused. TIme was the limiting factor.
# @Copyright: GNU
# @TODO: Roll into one script, clean up and make more efficient
# @Author: Jeff Masiello/Actionet Inc. 2014
# @Date: July 3, 2014
# @Version: 0.2
export PATH=$PATH:$EC2_HOME/bin
AMISNAP_HOME='/opt/amisnaps'
# current isntance we are assessing
currentInstance=""
# number of blockdevices attached to this instance
deviceCount=0
# current tag we are assessing, this shoudl be the name of the instance
currentTag=""
# holds the results of describe isntances
declare -a allData=()
# copies to keep (Not days)
retention=7

awsregions[0]="us-east-1"
awsregions[1]="us-west-1"
awsregions[2]="us-west-2"

# clean out of commands list
if [ -a $AMISNAP_HOME/commands.txt ]; then
	> $AMISNAP_HOME/commands.txt
fi

for region in "${awsregions[@]}"
do
    # collect all the info on all the instances we have which are running. We may want to add a non running instance list later. I'd
    # like to remove the need for files but don't knwo how to do that yet. I'm thinking arrays but *nix arrays are throwing me some curveballs
    # in regards to seperators. the following returns: e.g.
    # INSTANCE        i-a8d70089      ami-cbd9c7a2    ec2-54-84-112-57.compute-1.amazonaws.com        ip-172-31-13-98.ec2.internal    running NTERCore        0               m1.medium       2014-06-17T14:07:37+0000     us-east-1d      aki-805ea7e9                    monitoring-disabled     54.84.112.57    172.31.13.98    vpc-db06eabe    subnet-b01635f6 ebs                         paravirtual      xen     nGEYr1397569529395      sg-ee8a388b     default false
    # BLOCKDEVICE     /dev/sda1       vol-79f7d33b    2014-04-15T13:45:32.000Z        false
    # BLOCKDEVICE     /dev/sdf        vol-66f7d324    2014-04-15T13:45:32.000Z        false
    # TAG     instance        i-a8d70089      Name    P-repository.ntersupport.com
    # there can be multible BLOCKDEVICES or TAGS
    ec2-describe-instances --region $region --filter "instance-state-code=16" | grep -E "(^INSTANCE|^BLOCKDEVICE|^TAG.+Name)" | tee $AMISNAP_HOME/instances.txt

    # read the instances data and parse it
    while read aline
        do
            if [[ $aline =~ ^BLOCKDEVICE ]]; then
                #collect blockdevice info e.g. sda1, size and name
                            read cbd <<< $( echo $aline | awk '{print $3}' )
                allBlockDevices[$deviceCount]="$cbd"
                ((deviceCount++))
                cbd=""
            elif [[ $aline =~ ^TAG ]]; then
                #collect instance name. Also this is the last tag we collect before the new instance so we collect more detailed info here.
                # it would probably be better to have in the INSTANCE section for a cleaner divide but my bash skills aren't that good yet.
                            read currentTag <<< $(echo $aline | awk '{$1=$2=$3=$4="";print $0}')
                #collect volume specific information
                for volumeId in ${allBlockDevices[@]}; do
                    #returns the following and writes it to volumes.txt for parsing
                    #VOLUME  vol-decc0b9b    10      snap-79b573a5   us-east-1d      in-use  2014-06-02T13:58:18+0000        standard                Not Encrypted
                    #ATTACHMENT      vol-decc0b9b    i-88deb9db      /dev/sda1       attached        2014-06-02T13:58:18+0000        false
                    ec2-describe-volumes --region $region $volumeId | tee $AMISNAP_HOME/volumes.txt
                    # parse this volume directly
                    while read bline
                        do
                            if [[ $bline =~ ^VOLUME ]]; then
                                read volumeSize <<< $(echo $bline |  awk '{print $3}')
                            elif [[ $bline =~ ^ATTATCHMENT ]]; then
                                read mounting <<< $(echo $bline | awk '{print $4}')
                            fi
                    done < $AMISNAP_HOME/volumes.txt
                    # clear out old data
                    > $AMISNAP_HOME/volumes.txt
                    #concatenate to commands list for later inclusion in cron
                    echo "/opt/amisnaps/fssnap.sh $retention $volumeId $volumeSize x novalid \"$currentTag\" $region" >> $AMISNAP_HOME/commands.txt
                done

            elif [[ $aline =~ ^INSTANCE ]]; then
                #reset all parameters for next instance
                read currentInstance <<< $(echo $aline | awk '{print $2}')
                currentTag=volumeSize=mounting=""
                unset allBlockDevices
                deviceCount=0
            fi
    done < $AMISNAP_HOME/instances.txt
done

# clear out old isntances and write new cron
> $AMISNAP_HOME/fssnap_cron.sh

echo "#!/bin/bash" >> $AMISNAP_HOME/fssnap_cron.sh
echo "# backup file systems" >> $AMISNAP_HOME/fssnap_cron.sh
echo "# this file generated by fssnap_prop_cron.sh on $(date)" >> $AMISNAP_HOME/fssnap_cron.sh
echo "# see /opt/amisnaps/fssnap.sh commands below" >> $AMISNAP_HOME/fssnap_cron.sh
echo "function clean_up {" >> $AMISNAP_HOME/fssnap_cron.sh
echo "    # Perform program exit housekeeping" >> $AMISNAP_HOME/fssnap_cron.sh
echo "    echo \`/usr/bin/basename \$0\`\": SIGHUP, SIGINT, SIGTERM, or SIGQUIT caught; exiting\"" >> $AMISNAP_HOME/fssnap_cron.sh
echo "    exit" >> $AMISNAP_HOME/fssnap_cron.sh
echo "}" >> $AMISNAP_HOME/fssnap_cron.sh
echo "trap clean_up SIGHUP SIGINT SIGTERM SIGQUIT" >> $AMISNAP_HOME/fssnap_cron.sh
cat $AMISNAP_HOME/commands.txt >> $AMISNAP_HOME/fssnap_cron.sh
